package com.base.camel.tool.time;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 实现 统计分析，趋势图，默认时间打点获取
 */
public class TimeSeriesUtil {

    private static final Integer INIT_START_YEAR = 1;

    private static final Integer ONE_YEAR_DAYS = 365;

    private static final Integer ONE_YEAR_MONTHS = 12;

    private static final Integer ONE_DAY_HOURS = 24;

    private static final Integer DEFAULT_INIT_YEAR = 2;

    /**
     * 生成年序列 例如 key=2024
     * @return 时间序列
     */
    public static List<TimeSeries> generateYearSeries() {
        int num = DEFAULT_INIT_YEAR;
        FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy");
        return generateTimeSeries(TimeSeriesType.YEAR.getValue(), num, DateField.YEAR, fastDateFormat);
    }

    /**
     * 生成月序列 例如 key=2024-10
     * @return 时间序列
     */
    public static List<TimeSeries> generateMonthSeries() {
        int num = ONE_YEAR_MONTHS * DEFAULT_INIT_YEAR;
        return generateTimeSeries(TimeSeriesType.MONTH.getValue(), num, DateField.MONTH, DatePattern.NORM_MONTH_FORMAT);
    }

    /**
     * 生成天序列 例如 key=2024-10-10
     * @return 时间序列
     */
    public static List<TimeSeries> generateDaySeries() {
        int num = ONE_YEAR_DAYS * DEFAULT_INIT_YEAR;
        return generateTimeSeries(TimeSeriesType.DAY.getValue(), num, DateField.DAY_OF_YEAR, DatePattern.NORM_DATE_FORMAT);
    }

    /**
     * 生成小时序列 例如 key=2024-10-10 16
     * @return 时间序列
     */
    public static List<TimeSeries> generateHourSeries() {
        int num = ONE_YEAR_DAYS * ONE_DAY_HOURS * DEFAULT_INIT_YEAR;
        FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH");
        return generateTimeSeries(TimeSeriesType.HOUR.getValue(), num, DateField.HOUR, fastDateFormat);
    }


    /**
     * 根据不通时间类型分组要求构建  时间序列对象
     * @param type 分组类型 0 1 2 3 、0表示年  1表示月  2表示天  3表示小时
     * @param num  构建序列 点数数量
     * @param dateField 类型对应得步长类型
     * @param format 时间格式化 格式，对应type
     * @return 时间分组序列
     */
    private static List<TimeSeries> generateTimeSeries(String type, int num, DateField dateField, FastDateFormat format) {
        List<TimeSeries> timeSeriesList = new ArrayList<>();
        Date today = DateUtil.date();
        Date startTime = DateUtil.offsetDay(today, -ONE_YEAR_DAYS * INIT_START_YEAR);

        for (int i = 0; i < num; i++) {
            TimeSeries timeSeries = new TimeSeries();
            Date date = DateUtil.offset(startTime, dateField, i);
            timeSeries.setTimeKey(DateUtil.format(date, format));
            timeSeries.setTimeType(type);
            timeSeriesList.add(timeSeries);
        }
        return timeSeriesList;
    }


}
